# -*- encoding: utf-8 -*-
'''
@File    :   Exception.py   
@Contact :   desufnocs@163.com
@des     :   异常处理
 
@Modify Time       @Author      @Version    @Desciption
------------      ----------    --------    -----------
2025/2/17 14:15   AssenImpact      1.0         None
'''

from fastapi import Request, status
from fastapi.exceptions import RequestValidationError, HTTPException
from fastapi.responses import JSONResponse
from pydantic import ValidationError


async def HTTPException_error_handler(_: Request, exc: HTTPException):
    """
    异常报错
    :param _:
    :param exc:
    :return:
    """
    return JSONResponse(
        {
            "code": exc.status_code,
            "msg": exc.detail,
            "data": exc.detail,
        },
        status_code=exc.status_code,
        headers=exc.headers
    )


async def http422_error_handler(_: Request, exc: RequestValidationError | ValidationError) -> JSONResponse:
    """
    参数校验错误处理
    :param _:
    :param exc:
    :return:
    """
    return JSONResponse(
        {
            "code": status.HTTP_422_UNPROCESSABLE_ENTITY,
            "msg": f"数据校验错误 {exc.errors()}",
            "data": exc.errors(),
        },
        status_code=422,
    )
